import { PlusOutlined } from "@ant-design/icons";
import { ActionType, ProColumns, ProTable } from "@ant-design/pro-components";
import { Button, Form, Input, message, Modal } from "antd"
import { memo, useRef, useState } from "react";
import { projectCreate, projectDelete, projectList, projectUpdate } from "../api/request";
import { formatTime } from "@/utils/utils";


const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 17 },
};

const Project = () => {
    const actionRef = useRef<ActionType>();
    const [visibleCreate, setvisibleCreate] = useState(false);
    const [type, setType] = useState<'create' | 'update'>('create');
    const [form] = Form.useForm();
    const [projectData, setProjectData] = useState<ProjectData>(null!)
    const [loadding, setLoading] = useState<boolean>(null!)
    const formRef = useRef(null!)

    const columns: ProColumns<ProjectData>[] = [
        {
            title: '名称',
            dataIndex: 'name',
        },
        {
            title: '描述',
            dataIndex: 'describe',
        },
        {
            title: '修改时间',
            dataIndex: 'updatedTime',
            search: false,
            width: 230,
            render: (text, record,) => {
                return record.updatedTime && formatTime(record.updatedTime)
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createdTime',
            search: false,
            width: 230,
            render: (text, record,) => {
                return formatTime(record.createdTime)
            }
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            width: 230,
            render: (text, record, _, action) => [
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    location.href = `?projectId=${record.id}&projectName=${record.name}#/edit`
                }}>
                    编排
                </Button>,
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    window.open(`?projectId=${record.id}&projectName=${record.name}#/chat`, '_blank')
                }}>
                    聊天
                </Button>,
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    setType('update')
                    setvisibleCreate(true)
                    setProjectData(record)
                    form.setFieldsValue({
                        projectName: record.name,
                    })
                }}>
                    修改
                </Button>,
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    Modal.confirm({
                        title: '删除',
                        content: '是否删除',
                        onOk: async () => {
                            await projectDelete(record.id)
                            actionRef.current?.reload()
                            Modal.destroyAll();
                            message.success("删除成功")
                        }
                    })
                }}>
                    删除
                </Button>
            ],
        }
    ]

    return <div>
        <ProTable<ProjectData>
            columns={columns}
            actionRef={actionRef}
            headerTitle="智能体"
            cardBordered
            editable={{
                type: 'multiple',
            }}
            formRef={formRef}
            rowKey="id"
            options={{
                setting: {
                    listsHeight: 400,
                },
            }}
            pagination={{
                pageSize: 5
            }}
            request={async (params) => {
                return await projectList(params.projectName) as any
            }}
            dateFormatter="string"
            toolBarRender={() => [
                <Button
                    key="button"
                    icon={<PlusOutlined />}
                    onClick={() => (setvisibleCreate(true), setType("create"))}
                    type="primary"
                >
                    新建
                </Button>
            ]}
        />

        <Modal title={type == "create" ? "新建" : "修改"}
            open={visibleCreate}
            confirmLoading={loadding}
            onOk={() => {
                form.validateFields().then(async (values) => {
                    setLoading(true)
                    if (type == "create") {
                        const result = await projectCreate(values.projectName, values.describe)
                        if (result.code == 200) {
                            message.success('创建成功')
                            setLoading(false)
                        }
                        console.log(result)
                    } else {
                        const result = await projectUpdate(projectData.id, values.projectName, values.describe)
                        if (result.code == 200) {
                            message.success('修改成功')
                            setLoading(false)
                        }
                    }
                    actionRef.current?.reload()
                    setvisibleCreate(false)
                })
            }}
            onCancel={() => setvisibleCreate(false)}
            onClose={() => setvisibleCreate(false)}>
            <Form
                {...layout}
                form={form}
                style={{ maxWidth: 600 }}
                className="mt-6"
            >
                <Form.Item name="projectName" label="名称" rules={[{ required: true }]}>
                    <Input autoComplete="off" />
                </Form.Item>
                <Form.Item name="describe" label="描述">
                    <Input.TextArea autoComplete="off" />
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default memo(Project)